package com.cssl.util;
import com.cssl.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class SendMess {

    private static final String URL_TEMPLATE= "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     * @param mobile 短信接收人号码
     * @param value 短信发送的内容
     */
    public void send(String mobile,String value){
        System.out.println(smsConfig.getTemplateId());
        String url = String.format(URL_TEMPLATE,mobile,smsConfig.getTemplateId(),value);

        HttpHeaders httpHeaders = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        httpHeaders.set("Authorization","APPCODE "+smsConfig.getAppCode());

        HttpEntity entity = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        if(response.getStatusCode().is2xxSuccessful()){
            System.out.println("发送短信验证码成功");
        }else {
            System.out.println("发送短信验证码失败:{}"+response.getBody());
        }
    }
}
